<template>
  <div class="date-wrapper">
    <el-date-picker 
      v-model="localStartTime" 
      placeholder="选择开始日期" 
      :clearable="false" 
      :type="typeData" 
      :value-format="format"
      @change="changeStartTime">
    </el-date-picker>
    <span style="padding: 0 1px">至</span>
    <el-date-picker 
      v-model="localEndTime" 
      placeholder="选择结束日期" 
      :type="typeData" 
      :clearable="false" 
      :value-format="format"
      @change="changeEndTime">
    </el-date-picker>
  </div>
</template>

<script>
export default {
  name: 'DatePicker',
  props: {
    startTime: {
      type: String,
      default: ''
    },
    endTime: {
      type: String,
      default: ''
    },
    typeData: {
      type: String,
      default: 'date'
    },
    format: {
      type: String,
      default: 'yyyy-MM-dd'
    }
  },
  data() {
    return {
      localStartTime: this.startTime,
      localEndTime: this.endTime
    };
  },
  watch: {
    startTime(newVal) {
      this.localStartTime = newVal;
    },
    endTime(newVal) {
      this.localEndTime = newVal;
    }
  },
  methods: {
    changeStartTime(val) {
      this.localStartTime = val === null ? '' : val;
      if (this.localEndTime) {
        let enactDateBeginText = new Date(this.localStartTime).getTime();
        let enactDateEndText = new Date(this.localEndTime).getTime();
        if (enactDateBeginText > enactDateEndText) {
          this.$message.error('开始时间不得大于结束时间,请重新选择!');
          this.localStartTime = '';
        }
      }
      this.$emit('update:startTime', this.localStartTime);
      this.$emit('changeData', this.localStartTime, this.localEndTime);
    },
    changeEndTime(val) {
      this.localEndTime = val === null ? '' : val;
      if (this.localStartTime) {
        let enactDateBeginText = new Date(this.localStartTime).getTime();
        let enactDateEndText = new Date(this.localEndTime).getTime();
        if (enactDateBeginText > enactDateEndText) {
          this.$message.error('结束时间不可小于开始时间,请重新选择!');
          this.localEndTime = '';
        }
      }
      this.$emit('update:endTime', this.localEndTime);
      this.$emit('changeData', this.localStartTime, this.localEndTime);
    }
  }
};
</script>

<style lang="scss" scoped>
.date-wrapper {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .el-date-editor {
    .el-input__inner {
      padding: 0 0 0 10px !important;
    }

    .el-input__prefix {
      display: none;
    }

    .el-input__suffix {
      text-align: right;
    }
  }
}
</style>
